<template>
  <div>
    <el-drawer
      v-model="dialogFormVisible"
      :title="title"
      direction="rtl"
      size="60%"
      @close="close"
    >
      <el-row>
        <el-col :span="10">
          <el-form ref="form22" v-model="queryFormOrder2" label-width="70px">
            <el-form-item>
              <el-input
                v-model="queryFormOrder2.userinfo"
                rows="10"
                :clearable="true"
                size="medium"
                placeholder="请输入快捷识别用户的信息"
                type="textarea"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="shibie">一键识别</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14">
          <el-form
            ref="formRef"
            label-width="80px"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="学校" prop="schoolCode">
              <el-select
                v-model="form.schoolCode"
                filterable
                placeholder="请选择学校"
              >
                <el-option
                  v-for="(item, index) in schoolList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="层次" prop="cengci">
              <el-select v-model="form.cengci" placeholder="请选择层次">
                <el-option
                  v-for="(item, index) in cengciList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="是否需要学位">
              <el-radio-group v-model="need_xuewei">
                <el-radio label="1">需要</el-radio>
                <el-radio label="0">不需要</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="机构" prop="schoolCode">
              <el-select
                v-model="form.institutionName"
                filterable
                allow-create
                clearable
                placeholder="请选择机构"
              >
                <el-option
                  v-for="(item, index) in institutionList"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="学号" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="专业" prop="zhuanye">
              <el-input v-model="form.zhuanye" />
            </el-form-item>
            <el-form-item label="选题" prop="clue">
              <el-input v-model="form.clue" />
            </el-form-item>
            <el-form-item label="字数" prop="word_num">
              <el-input
                v-model="form.word_num"
                type="number"
                @mousewheel.prevent
              />
            </el-form-item>
            <el-form-item label="成交价" prop="amount">
              <el-input
                v-model="form.amount"
                type="number"
                prop="amount"
                @mousewheel.prevent
              />
            </el-form-item>
            <el-form-item
              v-if="is_edit == false"
              label="预付款"
              prop="received_amount"
            >
              <el-input
                v-model="form.received_amount"
                type="number"
                @mousewheel.prevent
              />
            </el-form-item>
            <el-form-item
              v-if="is_edit == false"
              label="返费金额"
              prop="reback_amount"
            >
              <el-input
                v-model="form.reback_amount"
                type="number"
                @mousewheel.prevent
              />
            </el-form-item>
            <el-form-item label="上传系统单">
              <el-radio-group v-model="is_upload_system">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="is_upload_system == '1'" label="登录账号">
              <el-input v-model="form.login_username" type="text" />
            </el-form-item>
            <el-form-item v-if="is_upload_system == '1'" label="登录密码">
              <el-input v-model="form.login_password" type="text" />
            </el-form-item>
            <el-form-item v-if="is_upload_system == '1'" label="登录地址">
              <el-input v-model="form.login_url" type="text" />
            </el-form-item>
            <el-form-item label="查重平台" prop="chachong_ruanjian">
              <el-select
                v-model="form.chachong_ruanjian"
                filterable
                allow-create
                clearable
                :reserve-keyword="false"
                placeholder="查重平台"
              >
                <el-option
                  v-for="item in chachong_ruanjian_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="查重率" prop="chachonglv">
              <el-select
                v-model="form.chachonglv"
                filterable
                allow-create
                clearable
                :reserve-keyword="false"
                placeholder="查重率"
              >
                <el-option
                  v-for="item in chachonglv_options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="截止日期" prop="diedline">
              <el-date-picker
                v-model="form.diedline"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD 23:59:59"
                :shortcuts="shortcuts"
                placeholder="截止日期"
              />
            </el-form-item>
            <el-form-item label="学校要求" prop="ask">
              <el-input v-model="form.ask" type="textarea" />
            </el-form-item>
            <el-form-item label="客户附件">
              <el-upload
                v-model:file-list="form.file_list"
                class="upload-demo"
                multiple
                :action="baseURL + '/api/file/file'"
              >
                <el-button type="primary">点击选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传文件附件，大小不超过10M
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <div style="text-align: center">
              <el-button @click="close">取 消</el-button>
              <el-button type="primary" @click="save">确 定</el-button>
            </div>
          </el-form>
        </el-col>
      </el-row>

      <template #footer></template>
    </el-drawer>
  </div>
</template>

<script>
  import { doEdit } from '@/api/boyiCustomer'

  import { parseTime } from '@/utils'
  import { baseURL } from '@/config'

  export default defineComponent({
    name: 'BoyiCustomerEdit',
    props: {
      schoolList: {
        type: Array,
        default: () => [],
      },
      institutionList: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        form: {
          is_upload_system: '0',
        },
        is_edit: false,
        queryFormOrder2: {
          userinfo: '',
        },
        is_upload_system: '0',
        need_xuewei: '0',
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        },
        title: '',
        dialogFormVisible: false,
        baseURL: baseURL,
        chachonglv_options: [
          { label: '10%', value: '10%' },
          { label: '20%', value: '20%' },
          { label: '30%', value: '30%' },
          { label: '40%', value: '40%' },
          { label: '50%', value: '50%' },
          { label: '60%', value: '60%' },
        ],
        chachong_ruanjian_options: [
          { label: '维普', value: '维普' },
          { label: '知网', value: '知网' },
          { label: '格子达', value: '格子达' },
        ],
        cengciList: [
          { label: '网教本科', value: '网教本科' },
          { label: '成教本科', value: '成教本科' },
          { label: '自考本科', value: '自考本科' },
          { label: '专科', value: '专科' },
        ],
        shortcuts: [
          {
            text: '今天',
            value: new Date(),
          },
          {
            text: '明天',
            value: () => {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              return date
            },
          },
          {
            text: '一周后',
            value: () => {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              return date
            },
          },
        ],
      })

      const shibie = () => {
        // 使用js提取姓名
        const mathcArr = [
          { name: '姓名', key: 'name' },
          { name: '登录账号', key: 'login_username' },
          { name: '登录密码', key: 'login_password' },
          { name: '登录地址', key: 'login_url' },
          { name: '学号', key: 'username' },
          { name: '专业', key: 'zhuanye' },
          // { name: '学校', key: 'schoolCode' },
          { name: '联系电话', key: 'tel' },
          { name: '指导教师', key: 'teacher' },
          { name: '层次', key: 'cengci' },
          { name: '选题', key: 'clue' },
          { name: '查重率', key: 'chachonglv' },
          { name: '班级', key: 'banji' },
          { name: '备注', key: 'remark' },
          { name: '字数', key: 'word_num' },
          { name: '成交价', key: 'amount' },
          { name: '返费金额', key: 'reback_amount' },
          { name: '查重平台', key: 'chachong_ruanjian' },
          { name: '截止日期', key: 'diedline' },
          { name: '学校要求', key: 'ask' },
          { name: '层次', key: 'cengci' },
        ]

        for (let i = 0; i < mathcArr.length; i++) {
          const matchResult = state.queryFormOrder2.userinfo.match(
            new RegExp(`${mathcArr[i].name}[：:、]?(.*?)([\\s\n]|$)`)
          )
          const value = matchResult ? matchResult[1] : ''
          state.form[mathcArr[i].key] = value
        }
        // 匹配学校
        let matchResult = state.queryFormOrder2.userinfo.match(
          new RegExp(`学校[：:、，]?(.*?)([\\s\n]|$)`)
        )
        const value = matchResult ? matchResult[1] : ''
        const school = props.schoolList.find((item) => item.name === value)
        if (school) {
          state.form.schoolCode = school.id
        }
        // 匹配层次

        matchResult = state.queryFormOrder2.userinfo.match(
          new RegExp(`是否需要学位[：:、，]?(.*?)([\\s\n]|$)`)
        )
        const xuewei = matchResult ? matchResult[1] : ''
        if (xuewei == '需要') {
          state.form.need_xuewei = '1'
          state.need_xuewei = '1'
        }
        if (xuewei == '不需要') {
          state.form.need_xuewei = '0'
          state.need_xuewei = '0'
        }
      }

      const showEdit = (row) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          state.is_edit = true
          row.diedline = parseTime(row.diedline, '{y}-{m}-{d}')

          state.is_upload_system = `${row.is_upload_system}`
          state.need_xuewei = `${row.need_xuewei}`

          // 遍历机构列表，判断row.institutionName是否存在，如果不存在则添加
          const institution = props.institutionList.find(
            (item) => item.id === row.institutionId
          )
          if (institution) {
            row.institutionName = institution.name
          }
          state.form = Object.assign({}, row)
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.is_edit = false
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            try {
              const file_id_list = []
              if (state.form.file_list && state.form.file_list.length > 0) {
                state.form.file_list.forEach((item) => {
                  file_id_list.push(item.id || item.response.data.id)
                })
              }

              state.form.file_id_list = file_id_list
              state.form.is_upload_system = state.is_upload_system
              state.form.need_xuewei = state.need_xuewei
              const { msg } = await doEdit(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
            } catch (error) {
              // $baseMessage(error.msg, 'success', 'vab-hey-message-error')
            }
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
        shibie,
        parseTime,
      }
    },
  })
</script>
